package com.example.sqlite;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import java.util.ArrayList;
import java.util.List;

public class AddressDaoResolver {
    private final String INFO_URI = "content://com.example.contentprovider/information";
    private ContentResolver resolver;
    private Uri uri;

    public AddressDaoResolver(Context context) {
        resolver = context.getContentResolver();
        this.uri = Uri.parse(INFO_URI);
    }

    public int insert(Address address) {
        ContentValues values = new ContentValues();
        values.put("name", address.getName());
        values.put("phone", address.getPhone());

        Uri insertUri = resolver.insert(uri, values);
        if(insertUri != null) {
            return Integer.parseInt(insertUri.getPathSegments().get(1));
        }
        return 0;
    }

    public boolean update(Address address) {
        Uri itemUri = Uri.parse(INFO_URI + "/" + address.get_id());
        ContentValues values = new ContentValues();
        values.put("name", address.getName());
        values.put("phone", address.getPhone());

        return resolver.update(itemUri, values, null, null) > 0;
    }

    public boolean delete(int _id) {
        Uri itemUri = Uri.parse(INFO_URI + "/" + _id);
        return resolver.delete(itemUri, null, null) > 0;
    }

    public List<Address> query() {
        List<Address> addresses = new ArrayList<>();
        Cursor cursor = resolver.query(this.uri, null, null, null, null);
        if (cursor != null) {
            while(cursor.moveToNext()) {
                int _id = cursor.getInt(cursor.getColumnIndex("_id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String phone = cursor.getString(cursor.getColumnIndex("phone"));
                addresses.add(new Address(_id, name, phone));
            }
            cursor.close();
        }
        return addresses;
    }
}
